import React from 'react';
import ReactDOM from 'react-dom';
import Loading from '@/components/Loading';
import Modal from '@/components/Modal';

class Tip {
  /**
   * 禁止滑动
   * @param selector 选择器
   */
  forbidSlide(selector: string) {
    const node = document.querySelector(selector);
    node &&
      node.addEventListener('touchmove', (e) => {
        e.preventDefault();
      });
  }

  loading(text, duraing) {
    // 清除已有 loading-wrap 弹窗，做到当前永远只保留一个 loading-wrap
    const nodes = document.querySelectorAll('#loading-wrap');
    nodes.forEach((item) => {
      item.parentNode.removeChild(item);
    });

    const nodeHandle = document.createElement('div');
    nodeHandle.setAttribute('id', 'loading-wrap');
    document.body.appendChild(nodeHandle);
    ReactDOM.render(<Loading text={text} />, nodeHandle);
    this.forbidSlide('#loading-wrap');
  }

  hideLoading() {
    // 清除已有 loading-wrap 弹窗，做到当前永远只保留一个 loading-wrap
    const nodes = document.querySelectorAll('#loading-wrap');
    nodes.forEach((item) => {
      item.parentNode.removeChild(item);
    });
  }

  /**
   *
   * @param title
   * @param content
   * @param btnGrp
   * @param data
   */
  showModal(title, content, btnGrp, data) {
    // 清除已有 my-modal 弹窗，做到当前永远只保留一个 my-modal
    const nodes = document.querySelectorAll('#my-modal');
    nodes.forEach((item) => {
      item.parentNode.removeChild(item);
    });

    const nodeHandle = document.createElement('div');
    nodeHandle.setAttribute('id', 'my-modal');
    document.body.appendChild(nodeHandle);
    ReactDOM.render(
      <Modal title={title} content={content} btnGrp={btnGrp} data={data} />,
      nodeHandle,
    );
    this.forbidSlide('#my-modal');
  }

  hideModal() {
    const nodes = document.querySelectorAll('#my-modal');
    nodes.forEach((item) => {
      item.parentNode.removeChild(item);
    });
  }
}

export default new Tip();
